use crate::dao;
use crate::models::models::components::v2ray::basic_setting::ComponentV2rayBasicSetting;
use crate::models::models::components::v2ray::dns_setting::ComponentV2rayDnsSetting;
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;

/// 获取DNS配置
pub(crate) fn get_dns_setting() -> Option<ComponentV2rayDnsSetting> {
    let value = get_setting_value("dns")?;

    // 解析JSON为结构
    let result = serde_json::from_str::<ComponentV2rayDnsSetting>(value.as_str());
    if result.is_err() {
        log::error!("解析配置失败: {}", result.unwrap_err().to_string());

        return None;
    }

    Some(result.unwrap())
}

/// 获取基础配置
pub(crate) fn get_basic_setting() -> Option<ComponentV2rayBasicSetting> {
    let value = get_setting_value("basic")?;

    // 解析JSON为结构
    let result = serde_json::from_str::<ComponentV2rayBasicSetting>(value.as_str());
    if result.is_err() {
        log::error!("解析配置失败: {}", result.unwrap_err().to_string());

        return None;
    }

    Some(result.unwrap())
}

/// 保存基础配置
pub(crate) fn set_basic_setting(setting: ComponentV2rayBasicSetting) -> MagicBoxResult<()> {
    let setting_value = serde_json::to_string(&setting);
    if setting_value.is_err() {
        log::error!("配置转换失败: {}", setting_value.unwrap_err().to_string());

        return Err(MagicBoxError::new(Code::UndefinedError, "配置转换失败"));
    }

    let connection = dao::connection::components::v2ray();

    let exists = get_basic_setting();
    if exists.is_some() {
        let result = connection.execute("update settings set value = ?1 where name = ?2", (setting_value.unwrap(), "basic"));
        if result.is_err() {
            let err = result.unwrap_err().to_string();
            log::error!("更新配置失败: {}", err.as_str());

            return Err(MagicBoxError::new(Code::UndefinedError, format!("更新配置失败: {}", err.as_str()).as_str()));
        }

        return Ok(());
    }

    let result = connection.execute("insert into settings (name, value) values (?1,?2)", ("basic", setting_value.unwrap()));
    if result.is_err() {
        let err = result.unwrap_err().to_string();
        log::error!("插入配置失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("插入配置失败: {}", err.as_str()).as_str()));
    }

    Ok(())
}

/// 获取配置项值
pub(crate) fn get_setting_value(name: &str) -> Option<String> {
    let connection = dao::connection::components::v2ray();

    // 查询数据
    let result = connection.prepare("select value from settings where name = ?1 limit 1").unwrap().query_row(&[&name], |row| {
        Ok(row.get::<_, String>(0)?)
    });

    if result.is_err() {
        log::error!("查询组件-V2ray配置失败: {}", result.unwrap_err().to_string());

        return None;
    }

    Some(result.unwrap())
}